<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition License
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magentocommerce.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Customer
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://www.magentocommerce.com/license/enterprise-edition
 */

/**
 * API2 class for customer address (customer)
 *
 * @category   Mage
 * @package    Mage_Customer
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Customer_Model_Api2_Customer_Address_Rest_Customer_V1 extends Mage_Customer_Model_Api2_Customer_Address_Rest
{
    /**
     * Create customer address
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     * @return string
     */
    protected function _create(array $data)
    {
        /* @var $customer Mage_Customer_Model_Customer */
        $customer = $this->_loadCustomerById($this->getApiUser()->getUserId());
        $validator = $this->_getValidator();

        if (!isset($data['firstname'])) {
            $data['firstname'] = $customer->getFirstname();
        }

        if (!isset($data['lastname'])) {
            $data['lastname'] = $customer->getLastname();
        }

        if (!is_array($data['street'])) {
            $data['street'] = array($data['street']);
        }

        $data = $validator->filter($data);
        if (!$validator->isValidData($data) || !$validator->isValidDataForCreateAssociationWithCountry($data)) {
            foreach ($validator->getErrors() as $error) {
                $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
            }
            $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
        }

        if (isset($data['region']) && isset($data['country_id'])) {
            $data['region'] = $this->_getRegionIdByNameOrCode($data['region'], $data['country_id']);
        }

        /* @var $address Mage_Customer_Model_Address */
        $address = Mage::getModel('customer/address');
        $address->setData($data);
        $address->setCustomer($customer);

        try {
            $address->save();
        } catch (Mage_Core_Exception $e) {
            $this->_error($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
        } catch (Exception $e) {
            $this->_critical(self::RESOURCE_INTERNAL_ERROR);
        }
        return array();
    }

    /**
     * Retrieve information about specified customer address
     *
     * @throws Mage_Api2_Exception
     * @return array
     */
    protected function _retrieve()
    {
        /* @var $address Mage_Customer_Model_Address */
        $address = $this->_getCollectionForRetrieve()->getFirstItem();

        $addressData = array(
            'firstname' => $address->getFirstname(),
            'mobile' => $address->getTelephone(),
            'address' => trim($address->getRegion()) . ' ' . trim($address->getCity()) . ' ' . trim($address->getStreetFull())
        );

        return $addressData;
    }

    /**
     * Get customer addresses list
     *
     * @return array
     */
    protected function _retrieveCollection()
    {
        $data = array();
        /* @var $address Mage_Customer_Model_Address */
        foreach ($this->_getCollectionForRetrieve() as $address) {
            //$addressData           = $address->getData();
            $addressData['id'] = $address->getId();
            $addressData['firstname'] = $address->getFirstname();
            $addressData['lastname'] = $address->getLastname();
            $addressData['region'] = $address->getRegion();
            $addressData['city'] = $address->getCity();
            $addressData['street'] = $address->getData('street');
            $addressData['postcode'] = $address->getPostcode();
            $addressData['telephone'] = $address->getTelephone();
            $data[] = array_merge($addressData, $this->_getDefaultAddressesInfo($address));
        }
        return $data;
    }

    /**
     * Retrieve collection instances
     *
     * @return Mage_Customer_Model_Resource_Address_Collection
     */
    protected function _getCollectionForRetrieve()
    {
        /* @var $customer Mage_Customer_Model_Customer */
        $customer = $this->_loadCustomerById($this->getApiUser()->getUserId());

        /* @var $collection Mage_Customer_Model_Resource_Address_Collection */
        $collection = $customer->getAddressesCollection();

        $this->_applyCollectionModifiers($collection);
        return $collection;
    }


    /**
     * Update specified stock item
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     */
    protected function _update(array $data)
    {
        /* @var $address Mage_Customer_Model_Address */
        $address = $this->_loadCustomerAddressById($this->getRequest()->getParam('id'));
        $validator = $this->_getValidator();

        if (!is_array($data['street'])) {
            $data['street'] = array($data['street']);
        }

        $data = $validator->filter($data);
        if (!$validator->isValidData($data, true)
            || !$validator->isValidDataForChangeAssociationWithCountry($address, $data)
        ) {
            foreach ($validator->getErrors() as $error) {
                $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
            }
            $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
        }
        if (isset($data['region'])) {
            $data['region'] = $this->_getRegionIdByNameOrCode(
                $data['region'], isset($data['country_id']) ? $data['country_id'] : $address->getCountryId()
            );
            $data['region_id'] = null; // to avoid overwrite region during update in address model _beforeSave()
        }

        $address->addData($data);

        try {
            $address->save();
        } catch (Mage_Core_Exception $e) {
            $this->_error($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
        } catch (Exception $e) {
            $this->_critical(self::RESOURCE_INTERNAL_ERROR);
        }
        return array();
    }

    /**
     * Delete customer
     */
    protected function _delete()
    {
        /* @var $address Mage_Customer_Model_Address */
        $address = $this->_loadCustomerAddressById($this->getRequest()->getParam('id'));

        if ($this->_isDefaultBillingAddress($address) || $this->_isDefaultShippingAddress($address)) {
            $this->_critical(
                'Address is default for customer so is not allowed to be deleted',
                Mage_Api2_Model_Server::HTTP_BAD_REQUEST
            );
        }
        try {
            $address->delete();
        } catch (Mage_Core_Exception $e) {
            $this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
        } catch (Exception $e) {
            $this->_critical(self::RESOURCE_INTERNAL_ERROR);
        }
        return array();
    }

    /**
     * Load customer address by id
     *
     * @param int $id
     * @throws Mage_Api2_Exception
     * @return Mage_Customer_Model_Address
     */
    protected function _loadCustomerAddressById($id)
    {
        /* @var $customerAddress Mage_Customer_Model_Address */
        $customerAddress = parent::_loadCustomerAddressById($id);
        // check owner
        if ($this->getApiUser()->getUserId() != $customerAddress->getCustomerId()) {
            $this->_critical(self::RESOURCE_NOT_FOUND);
        }
        return $customerAddress;
    }

    /**
     * Load customer by id
     *
     * @param int $id
     * @throws Mage_Api2_Exception
     * @return Mage_Customer_Model_Customer
     */
    protected function _loadCustomerById($id)
    {
        /* @var $customer Mage_Customer_Model_Customer */
        $customer = parent::_loadCustomerById($id);
        // check customer accaunt owner
        if ($this->getApiUser()->getUserId() != $customer->getId()) {
            $this->_critical(self::RESOURCE_NOT_FOUND);
        }
        return $customer;
    }
}
